// @ 516
// 表格衍生图表
// table chart show

let tableChart = {
    elmts: null,
    chart: null,
    parent: null,
    init: function( params ) {
        let _this = this;
        _this.elmts = params.elmts;
        _this.parent = params.parent;

        // 初始化函数加载
        _this.render( params );
    },
    view: function() {
        let _this = this,
            optionView = ``,
            callBack = { view: ``, parent: null };

        // 根据视图是否存在返回对应内容
        if ( !_this.parent.querySelector(".dataChart") ) {
            callBack.view += `<div class="dataChart">
                                            <div id="_chart"></div>
                                        </div>`;
        } else {
            callBack.view = optionView;
            callBack.parent = _this.parent.querySelector("select[name='changeElmt']");
        }

        optionView = null;

        return callBack;
    },
    render: function( params ) {
        let _this = this,
            thisView = _this.view(),
            requertParam = _this.getParam( params );

        // 根据视图是否存在添加相应内容
        if ( !_this.parent.querySelector(".dataChart") ) {
            _this.parent.insertAdjacentHTML( 'beforeEnd', thisView.view );
        }

        let loadMask = layLayer.load(0, {shade: [0.3, '#000']}),
            _thisElmtType = Cimiss.elmts[ requertParam.chart.elmt ];

        if ( _thisElmtType == "AgmeEle" ) {

            _this.getElmtCurDatas(
                requertParam.cimiss
            ).then( ( value ) => {
                requertParam['datas'] = value.DS;
            let newData = _this.resetData( requertParam );

            layLayer.close( loadMask );

            _this.renderChart({
                text: value.fieldNames,
                subtext: requertParam.chart.startTime +" ~ "+ requertParam.chart.endTime,
                xAxis: newData.xAxis,
                yAxis: value.fieldUnits,
                legends: newData.legends,
                series: newData.seriesData
            });
        }).catch( error => {
                console.log( JSON.stringify( error ) );
        });

        }else if(_thisElmtType.indexOf("TempHour")>-1){
            _this.getElmtCurDatas(
                requertParam.cimiss
            ).then( ( value ) => {
                requertParam['datas'] = value.DS;
            let newData = _this.resetData( requertParam );
            var m=value.dataMap;
            var series=[];
            var echartType='line';
            if(_thisElmtType=='Rain-TempHour'){
                echartType='bar';
            }
            for (var [name, val] of m) {
                series.push({
                    name: name ,
                    type: echartType,
                    data: val
                });
            }
            layLayer.close( loadMask );

            _this.renderChart({//传参渲染
                text: value.fieldNames,
                subtext: requertParam.chart.startTime +" ~ "+ requertParam.chart.endTime,
                xAxis: value.xdata,
                yAxis: value.fieldUnits,
                legends: value.stationName,
                series: series
            });
        }).catch( error => {
                console.log( JSON.stringify( error ) );
        });
        }
        else if ( _thisElmtType == "SurfEle" ) {

            Promise.all([
                _this.getElmtCurDatas( requertParam.cimiss ),
                _this.getElmtHistoryDatas( requertParam, "overYear" ),
                _this.getElmtHistoryDatas( requertParam, "lastYear" )
            ]).then( ( values ) => {
                requertParam.chart['legends'] = [ values[0].fieldNames, '历年值', '去年值' ];
            requertParam['datas'] = [ values[0].DS, values[1].obj, values[2].obj ];
            let newData = _this.resetData( requertParam );

            layLayer.close(loadMask);

            _this.renderChart({
                text: '站点要素综合展示',
                subtext: requertParam.chart.startTime +" ~ "+ requertParam.chart.endTime,
                xAxis: newData.xAxis,
                yAxis: values[0].fieldUnits,
                legends: requertParam.chart.legends,
                series: newData.seriesData
            });
        }).catch( error => {
                console.log( JSON.stringify( error ) );
        });

        } if ( requertParam.chart.elmt == "WinterWheat_syn" ) {
            _this.getCropSYNDatas( requertParam ).then( ( values ) => {
                requertParam.chart['legends'] = [ "适宜度", '去年同期', '过去五年' ];
            requertParam['datas'] = values.data;
            let newData = _this.resetData( requertParam );

            layLayer.close( loadMask );

            _this.renderChart({
                text: '生育期适宜度趋势',
                subtext: requertParam.chart.startTime +" ~ "+ requertParam.chart.endTime,
                xAxis: newData.xAxis,
                yAxis: "适宜度",
                max: 1,
                min: 0,
                legends: requertParam.chart.legends,
                series: newData.seriesData
            });
        }).catch( error => {
                console.log( JSON.stringify( error ) );
        });
        }
    },
    getElmtCurDatas: function( params ) {
        return new Promise( ( resolve, reject ) => {
            Cimiss.getCimissData(
            params,
            {
                callback: ( z, result ) => {
                if ( result.DS ) {
            resolve( result );
        } else {
            reject( "数据查询失败" );
        }
    }
    });
    });
    },
    getElmtHistoryDatas: function( params, type ) {
        let _this = this,
            api = "http://10.172.13.58:8088/ylsmsapi/getSurfEleInHistoryBySamePeriodAndStaID?",
            login = "userId=BEXA_YGZX_sxnqzx&pwd=81619505",
            data = "&dataFormat=json",
            interface = "&interfaceId=getSurfEleInHistoryBySamePeriodAndStaID",
            dataCode = "&dataCode=SURF_CHN_MUL_DAY",
            staids = "&staids="+ params.stationId.join(","),
            elements = "&elements=Year,Mon,Day,"+ params.chart.elmt,
            startTime = _this.timeRange({
                time: params.chart.startTime,
                type: "cimiss,MonDay"
            }),
            endTime = _this.timeRange({
                time: params.chart.endTime,
                type: "cimiss,MonDay"
            }),
            curYear = params.chart.endTime.split("年")[0],
            prevYear = ( type == "overYear" ) ? 1981 : curYear - 1,
            dataTimes = "&minYear="+ prevYear +"&maxYear="+ curYear +"&minMD="+ startTime +"&maxMD="+ endTime,
            _thisUrl = api + login + data + interface + dataCode + staids + elements + dataTimes;

        return new Promise( ( resolve, reject ) => {
            $.ajax({
            url: _thisUrl,
            type: "get",
            dataType: "json",
            async: false,
            success: function( result ) {
                if ( result ) {
                    resolve( result );
                } else {
                    reject( "数据查询失败" );
                }
            },
            error: function( error ) {
                reject( error );
            }
        });
    });
    },
    getCropSYNDatas: function( params ) {
        let _this = this,
            urlPath = "http://10.172.13.58:8088/MDRMSWebService/statis/wheatsuit?",
            timeRange = params.cimiss.timeRange.split(","),
            param = "stationId="+ params.stationId.join(",") +"&startTime="+ timeRange[0] +"&endTime="+ timeRange[1];

        return new Promise( ( resolve, reject ) => {
            $.ajax({
            url: urlPath + param,
            type: "get",
            dataType: "json",
            success: function( result ) {
                if ( result ) {
                    resolve( result );
                } else {
                    reject( "数据查询失败" );
                }
            },
            error: function( error ) {
                reject( error );
            }
        });
    });
    },
    getParam: function( params ) {
        let _this = this,
            type = null, station = [],
            stationId = [], stationName = [];

        // 重新构建站点结构
        for ( let x = 0; x < params.station.length; x++ ) {
            station.push({
                id: Number( params.station[x]["站号"] ),
                name: params.station[x]["名称"]
            });
        }

        // 根据站点id排序
        station = station.sort( ( a, b ) => { return a.id - b.id });

        // 根据排序后结构添加数据
        for ( let x = 0; x < station.length; x++ ) {
            stationId.push( station[x].id );
            stationName.push( station[x].name );
        }

        // 判断当前时间类型赋值
        let timeType = "cimiss,";

        let curTime = _this.getCurTime(),
            startTime = _this.timeRange({
                time: curTime.start,
                type: timeType + curTime.type
            }),
            endTime = _this.timeRange({
                time: curTime.end,
                type: timeType + curTime.type
            });

        return {
            timeType: curTime.type,
            stationId: stationId,
            stationName: stationName,
            cimiss: {
                staids: stationId.join(","),
                elements: params.curElmt.eleCode,
                timeRange: startTime +','+ endTime
            },
            chart: {
                elmt: params.curElmt.eleCode,
                theme: params.curElmt.chartTheme,
                startTime: curTime.start,
                endTime: curTime.end
            }
        };
    },
    resetData: function( params ) {
        let _this = this,
            callBack = {
                xAxis: [],
                legends: params.stationName,
                seriesData: []
            },
            range = 1,
            newData = params.datas,
            element = params.chart.elmt,
            chartTheme = params.chart.theme,
            overYear = 1981,
            startTime = params.chart.startTime,
            endYear = Number( params.chart.endTime.split("年")[0] ),
            incOrDecTime = new Date( _this.timeRange({
                time: startTime,
                type: "cimiss,"+params.timeType+",/"
            }) ).getTime();

        // 根据时间类型赋值
        switch( params.timeType ) {
            case "DayTimeType":
                range = 24 * 60 * 60 * 1000;
                break;
            case "HourTimeType":
                range = 60 * 60 * 1000;
                break;
        }

        // 根据条件重置数据结构
        let dataLent = newData.length / params.stationId.length;

        if ( Cimiss.elmts[ element ] == "AgmeEle" ) {
            dataLent = dataLent / 20;
            callBack.legends = [];

            for ( let x = 1; x < 7; x++ ) {
                let thisSeries = {
                    name: x * 10 +"CM",
                    type: chartTheme.toLowerCase(),
                    data: []
                };

                callBack.legends.push( x * 10 +"CM" );

                for ( let y = x; y < newData.length; y++ ) {
                    if ( Number( newData[y]["Soil_Depth_BelS"] ) <= 60 ) {
                        thisSeries.data.push( newData[y][element] );
                    }
                    y += 6;
                }

                if ( chartTheme == "LINE" ) thisSeries["smooth"] = true;

                callBack.seriesData.push( thisSeries );
                thisSeries = null;
            }

            for ( let x = 0; x < dataLent; x++ ) {
                callBack.xAxis.push( _this.timeRange({
                    time: incOrDecTime + x * range,
                    type: params.timeType+",/"
                }) );
            }
        } else if ( Cimiss.elmts[ element ] == "SurfEle" ) {
            dataLent = newData[0].length;
            let legends = params.chart.legends;
            for ( let x = 0; x < legends.length; x++ ) {
                let thisSeries = {
                    name: legends[x],
                    type: chartTheme.toLowerCase(),
                    data: []
                };

                if ( x == 0 ) {
                    for ( let y = 0; y < newData[x].length; y++ ) {
                        thisSeries.data.push( newData[x][y][element] );
                    }
                } else {
                    let _data = _this.objTimeCompare( newData[x][element] );

                    for ( let y = 0; y < _data.length; y++ ) {
                        let avg_val = null,
                            this_val = Number( newData[x][element][ _data[y] ][0] );

                        if ( x == 1 ) {
                            avg_val = this_val / ( endYear - overYear );
                        } else {
                            avg_val = this_val / 2;
                        }

                        thisSeries.data.push( Math.round( avg_val * 10 ) / 10 );
                    }
                }

                if ( chartTheme == "LINE" ) thisSeries["smooth"] = true;

                callBack.seriesData.push( thisSeries );
                thisSeries = null;
            }

            for ( let x = 0; x < dataLent; x++ ) {
                callBack.xAxis.push( _this.timeRange({
                    time: incOrDecTime + x * range,
                    type: params.timeType+",/"
                }) );
            }
        } else if ( element == "WinterWheat_syn" ) {
            let legends = params.chart.legends,
                _thisType = [ "SYNSUIT", "SYNSUIT_LAST", "SYNSUIT_PAST" ];

            let _data = newData.sort( _this.objCompare( "TEN" ) )
                .sort( _this.objCompare( "MONTH" ) )
                .sort( _this.objCompare( "YEAR" ) );

            for ( let x = 0; x < legends.length; x++ ) {
                let thisSeries = {
                    name: legends[x],
                    type: chartTheme.toLowerCase(),
                    data: []
                };

                for ( let y = 0; y < _data.length; y++ ) {
                    thisSeries.data.push( _data[y][ _thisType[x] ] );
                }

                if ( chartTheme == "LINE" ) thisSeries["smooth"] = true;

                callBack.seriesData.push( thisSeries );
                thisSeries = null;
            }

            let xun = [ "_", "上旬", "中旬", "下旬" ];
            for ( let x = 0; x < _data.length; x++ ) {
                let _year = _data[x].YEAR + "年",
                    _month = _data[x].MONTH + "月",
                    _xun = xun[ _data[x].TEN ];

                callBack.xAxis.push( _year + _month + _xun );
            }
        }

        return callBack;
    },
    renderChart: function( params ) {
        let _this = this,
            option = null;

        _this.chart = echarts.init( _this.parent.querySelector("#_chart") );

        option = {
            title: {
                show: true,
                text: params.text || "",
                subtext: params.subtext || "",
                left: 'center'
            },
            tooltip : {
                trigger: 'axis',
                axisPointer : { type : 'shadow' }
            },
            grid: {
                top: 70,
                left: 60,
                right: 20,
                bottom: 50,
                containLabel: false
            },
            xAxis : [{
                type : 'category',
                data : params.xAxis || [],
                axisTick: { alignWithLabel: true }
            }],
            yAxis: [{
                max: params.max || null,
                min: params.min || null,
                name: params.yAxis || "单位",
                type: 'value',
                axisPointer: { snap: true }
            }],
            legend: {
                data: params.legends || [],
                x: 'center', y: 'bottom'
            },
            series: params.series || []
        };

        _this.chart.clear();
        _this.chart.setOption( option );
        option = null;
    },
    getCurTime: function() {
        let _this = this,
            _thisTimeTpye = [
                "HourTimeType",
                "DayTimeType",
                "WeekTimeType",
                "TenDaysTimeType",
                "MonthTimeType",
                "SeasonTimeType",
                "YearTimeType"
            ];

        let _thisType = null;
        for ( let x = 0; x < _thisTimeTpye.length; x++ ) {
            let _thisElmt = document.querySelectorAll( "."+ _thisTimeTpye[x] );
            if ( _thisElmt.length > 0 ) {
                if (
                    ( _thisElmt[0].style.display == "block" || _thisElmt[0].style.display == "" )
                    && ( _thisElmt[1].style.display == "block" || _thisElmt[0].style.display == "" )
                ) {
                    _thisType = _thisTimeTpye[x];
                    break;
                }
            }
        }

        let timeBox = document.querySelectorAll( "."+ _thisType ),
            startTime = timeBox[0].querySelector(".input-start-time").value,
            endTime = timeBox[1].querySelector(".input-end-time").value;

        if ( _thisType == "TenDaysTimeType" ) {
            let TEN_s = timeBox[0].querySelectorAll("input")[1].value,
                TEN_e = timeBox[1].querySelectorAll("input")[1].value;

            switch( TEN_s ) {
                case "上旬": TEN_s = "01日"; break;
                case "中旬": TEN_s = "11日"; break;
                case "下旬": TEN_s = "21日"; break;
            }

            switch( TEN_e ) {
                case "上旬": TEN_e = "01日"; break;
                case "中旬": TEN_e = "11日"; break;
                case "下旬": TEN_e = "21日"; break;
            }

            startTime += TEN_s;
            endTime += TEN_e;
        }
        //else if(_thisType == "HourTimeType"){
        //var  _year = new Date().getFullYear();
        // var _month = new Date().getMonth()+1 ;
        //var m=_month<10?"0"+_month:_month;
        //var _date = new Date().getDate()-1;
        //var _hour = new Date().getHours();
        //var hour=_hour<10?"0"+_hour:_hour;
        //startTime=_year+"年"+m+"月"+_date+"日"+hour+"时";
        //startTime="2019年04月20日16时";
        //endTime="2019年04月21日16时";
        //}

        return {
            type: _thisType,
            start: startTime,
            end: endTime
        };
    },
    timeRange: function( params ) {
        let _this = this,
            _time = new Date(),
            _year = _time.getFullYear(),
            _month = _time.getMonth() + 1,
            _date = _time.getDate(),
            _hour = _time.getHours(),
            _time_ = null,
            _type = params.type.split(",");

        if ( params.time ) {
            if ( params.time != "" && _type[0] != "cimiss" ) {
                _time = new Date( params.time );
                _year = _time.getFullYear();
                _month = _time.getMonth() + 1;
                _date = _time.getDate();
                _hour = _time.getHours();
            } else if ( params.time != "" && _type[0] == "cimiss" ) {
                _time = params.time;
                _year = _time.split("年");
                _month = _year[1].split("月");
                _date = _month[1].split("日");
                _hour = _date[1].split("时");
            }
        }

        switch( params.type ) {
            case "cimiss,HourTimeType":
                _time_ = "" + _year[0] + _month[0] + _date[0] + _hour[0] + "0000";
                break;
            case "cimiss,DayTimeType":
                _time_ = "" + _year[0] + _month[0] + _date[0] + "000000";
                break;
            case "cimiss,HourTimeType,/":
                _time_ = _year[0] +"/"+ _month[0] +"/"+ _date[0] +" "+ _hour[0] +":00";
                break;
            case "cimiss,DayTimeType,/":
                _time_ = _year[0] +"/"+ _month[0] +"/"+ _date[0];
                break;
            case "cimiss,TenDaysTimeType":
                _time_ = "" + _year[0] + _month[0] + _date[0];
                break;
            case "cimiss,MonDay":
                _time_ =  _month[0] +""+ _date[0];
                break;
            case "HourTimeType,/":
                _time_ = _year+"/"+ _month +"/"+ _date +" "+ _hour +":00";
                break;
            case "DayTimeType,/":
                _time_ = _year+"/"+ _month +"/"+ _date;
                break;
            case "MonDay":
                _time_ =  _month[0] +""+ _date[0];
                break;
            case ",TenDaysTimeType":
                _time_ = _year+""+ _month +""+ _date;
                break;
        }

        return _time_;
    },
    objCompare: function( prop ) {
        return function ( obj1, obj2 ) {
            var val1 = Number( obj1[ prop ] ),
                val2 = Number( obj2[ prop ] );

            if ( val1 < val2 ) {
                return -1;
            } else if ( val1 > val2 ) {
                return 1;
            } else {
                return 0;
            }
        }
    },
    objTimeCompare: function( arrys ) {
        let _this = this,
            sortVal = [],
            newArrys = [];

        for ( let x in arrys ) {
            newArrys.push( arrys[x][1]+"-"+x );
        }

        sortVal = newArrys.sort( ( a,b ) => {
            return new Date( a ).getTime() - new Date( b ).getTime();
    });

        for ( let x = 0; x < sortVal.length; x++ ) {
            let lent = sortVal[x].length;
            sortVal[x] = sortVal[x].substring( 5, lent );
        }

        return sortVal;
    },
    listenerSelect: function( param ) {
        let _this = this;

        param.elmt.addEventListener( 'change', function( e ) {
            param.callBack( e );
        }, false);
    }
};